package com.ec.pf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ec.pf.pojo.ElderlyProfile;
import com.ec.pf.service.ElderlyProfileService;
import com.ec.common.exception.BadRequestException;
import com.ec.common.exception.BusinessException;
import com.ec.common.exception.DbException;
import com.ec.common.exception.UnauthorizedException;
import com.ec.common.domain.Result;
import com.ec.common.enumeration.BusinessExceptionEnum;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;

@RestController
@RequestMapping("/elderly")
public class ElderlyProfileController {

    @Autowired
    private ElderlyProfileService elderlyProfileService;

    /**
     * 新增老人档案
     */
    @PostMapping
    public Result<ElderlyProfile> addElderlyProfile(@RequestBody ElderlyProfile elderlyProfile) {
        try {
            // 设置 created_at 和 updated_at 为当前时间
            Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
            elderlyProfile.setCreatedAt(currentTimestamp);
            elderlyProfile.setUpdatedAt(currentTimestamp);

            // 调用 Service 层保存老人档案
            ElderlyProfile result = elderlyProfileService.addElderlyProfile(elderlyProfile);
            return Result.ok(result);
        } catch (BusinessException e) {
            throw new BusinessException(BusinessExceptionEnum.PARAM_ERROR); // Example of BusinessException
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }

    /**
     * 根据ID删除老人档案
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteElderlyProfile(@PathVariable Long id) {
        try {
            boolean success = elderlyProfileService.deleteElderlyProfileById(id);
            if (success) {
                return Result.ok();
            } else {
                throw new BadRequestException("删除失败，未找到该老人档案");
            }
        } catch (BadRequestException e) {
            throw e;
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }

    /**
     * 修改老人档案
     */
    @PutMapping("/{id}")
    public Result<ElderlyProfile> updateElderlyProfile(@PathVariable Long id, @RequestBody ElderlyProfile elderlyProfile) {
        try {
            elderlyProfile.setId(id);

            // 显式设置 updatedAt 字段
            elderlyProfile.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

            ElderlyProfile result = elderlyProfileService.updateElderlyProfile(elderlyProfile);

            return Result.ok(result);
        } catch (BusinessException e) {
            throw new BusinessException(BusinessExceptionEnum.PARAM_ERROR);
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询老人档案
     */
    @GetMapping("/{id}")
    public Result<ElderlyProfile> getElderlyProfile(@PathVariable Long id) {
        try {
            ElderlyProfile elderlyProfile = elderlyProfileService.getElderlyProfileById(id);
            return Result.ok(elderlyProfile);
        } catch (BadRequestException e) {
            throw e;
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }

    /**
     * 分页查询老人档案
     */
    @GetMapping("/list")
    public Result<Page<ElderlyProfile>> listElderlyProfiles(@RequestParam Integer page, @RequestParam Integer size) {
        try {
            Page<ElderlyProfile> elderlyProfiles = elderlyProfileService.listElderlyProfiles(page, size);
            return Result.ok(elderlyProfiles);
        } catch (UnauthorizedException e) {
            throw e;
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }

    /**
     * 模糊查询老人档案
     */
    @GetMapping("/search")
    public Result<Page<ElderlyProfile>> searchElderlyProfiles(@RequestParam(required = false) String fullName,
                                                              @RequestParam(required = false) String idCardNumber,
                                                              @RequestParam(required = false) String gender,
                                                              @RequestParam int page,
                                                              @RequestParam int size) {
        try {
            // 调用 service 层方法进行模糊查询
            Page<ElderlyProfile> elderlyProfiles = elderlyProfileService.searchElderlyProfiles(fullName, idCardNumber, gender, page, size);
            return Result.ok(elderlyProfiles);
        } catch (UnauthorizedException e) {
            throw e;
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }


    /**
     * 批量删除老人档案
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteElderlyProfiles(@RequestBody List<Long> ids) {
        try {
            boolean success = elderlyProfileService.batchDeleteElderlyProfiles(ids);
            if (success) {
                return Result.ok();
            } else {
                throw new BadRequestException("批量删除失败");
            }
        } catch (BadRequestException e) {
            throw e;
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }

    /**
     * 更新老人状态（如：在住、退住、临时外出）
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateElderlyStatus(@PathVariable Long id, @RequestParam String status) {
        try {
            boolean success = elderlyProfileService.updateElderlyCheckInStatus(id, status);
            if (success) {
                return Result.ok();
            } else {
                throw new BusinessException(BusinessExceptionEnum.PARAM_ERROR);
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }

    /**
     * 更新老人状态（如：在住、退住、临时外出）通过user_id
     */
    @PutMapping("/{id}/status/user_id")
    public Result<Void> updateElderlyStatusByUserId(@PathVariable Long id, @RequestParam String status) {
        try {
            // 根据user_id查询老人档案，不是根据id查询
            ElderlyProfile profile = elderlyProfileService.getOne(new QueryWrapper<ElderlyProfile>().eq("user_id", id));
            if (profile == null) {
                throw new BadRequestException("老人档案不存在");
            }
            profile.setCheckInStatus(status);
            boolean success = elderlyProfileService.updateById(profile);
            if (success) {
                return Result.ok();
            } else {
                throw new BusinessException(BusinessExceptionEnum.PARAM_ERROR);
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new DbException("数据库错误: " + e.getMessage());
        }
    }

    /**
     * 更新老人床位ID
     */
    @ApiOperation(value = "更新床位ID", notes = "更新老人档案的床位ID")
    @PatchMapping("/{id}/bed")
    public Result<Boolean> updateBedId(@PathVariable("id") Long id, @RequestParam("bedId") Long bedId) {
        // 根据user_id查询老人档案，不是根据id查询
        ElderlyProfile profile = elderlyProfileService.getOne(new QueryWrapper<ElderlyProfile>().eq("user_id", id));
        if (profile == null) {
            throw new BadRequestException("老人档案不存在");
        }
        // bedId 可能为 -1
        if (bedId == (long) -1) {
            profile.setBedId(null);
        } else {
            profile.setBedId(Math.toIntExact(bedId));
        }

        ElderlyProfile updatedProfile = elderlyProfileService.updateElderlyProfile(profile);
        return Result.ok(updatedProfile != null);
    }
}
